package org.apache.servicecomb.samples.practise.houserush.customer.manage.service;

import org.apache.servicecomb.provider.pojo.RpcReference;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.aggregate.Customer;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.aggregate.Qualification;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.dao.CustomerDao;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.rpc.HouseOrderApi;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.rpc.UserApi;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.rpc.po.SaleQualification;
import org.apache.servicecomb.samples.practise.houserush.customer.manage.rpc.po.User;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/19 22:11
 * @Description:
 */
@Service
public class CustomerManageServiceImpl implements CustomerManageService {

    @Autowired
    private CustomerDao customerDao;

    @RpcReference(microserviceName = "house-order", schemaId = "houseOrderApiRest")
    private HouseOrderApi houseOrderApi;

    @RpcReference(microserviceName = "login", schemaId = "userApiRest")
    private UserApi userApi;

    //根据id查询客户
    public Customer findCustomer(int id) {
        return customerDao.findOne(id);
    }

    //查询所有客户
    public List<Customer> indexCustomers() {
        return customerDao.findAll();
    }

    //创建客户
    @Transactional
    public Customer createCustomer(Customer customer) {
        //1.login创建用户，返回用户的自增id
        User user = new User();
        user.setUsername(customer.getName());
        user.setPassword("123456");
        User user1 = userApi.createUser(user);

        //2.活动资格处理
        List<SaleQualification> saleQualificationArrayList = new ArrayList<>();

        //遍历活动资格
        customer.getQualifications().forEach(qualification -> {
            //设置活动客户id
            Customer c = new Customer();
            c.setId(user1.getId());
            qualification.setCustomer(c);

            //设置活动客户id，活动id和房源总数 houseOrder
            SaleQualification saleQualification = new SaleQualification();
            saleQualification.setCustomerId(user1.getId());
            saleQualification.setSaleId(qualification.getSaleId());
            //计算活动下的所有房源数
            int countHouseBySale = houseOrderApi.countHouseBySaleId(qualification.getSaleId());
            saleQualification.setQualificationCount(countHouseBySale);
            saleQualificationArrayList.add(saleQualification);
        });
        //保存客户信息表，并级联保存了活动资格表 houserush_customer
        customer.setId(user1.getId());
        customer = customerDao.save(customer);
        //保存活动资格表 houseOrder
        houseOrderApi.updateSaleQualification(saleQualificationArrayList);

        return customer;
    }


    //根据id修改客户信息
    public Customer updateCustomer(Customer customer) {
        //获取客户id
        Integer customerId = customer.getId();

        //判断数据库表中是否有该客户
        if (customerDao.exists(customerId)) {
            //如果有该客户就进行修改
            //删除house-order中活动信息(清理活动数据)
            houseOrderApi.removeSaleQualification(customerId);
            //更新客户和客户的活动信息(再次保存新的活动数据)
            updateCustomerQualifications(customer, customer.getQualifications());
            return customer;
        } else {
            //如果没有，抛异常通知
            throw new DataRetrievalFailureException("不能修改不存在的数据");
        }
    }


    //更新新客户和客户的活动资格信息
    @Transactional
    public Boolean updateCustomerQualifications(Customer customer, List<Qualification> qualifications) {
        //给客户设置活动资格数据
        customer.setQualifications(qualifications);
        //给活动资格设置客户信息
        qualifications.forEach(qualification -> qualification.setCustomer(customer));
        //保存客户数据，级联保存的，同时保存两张表的数据customers和qualifications
        customerDao.saveAndFlush(customer);

        //准备house-order需要进行冗余保存的活动资格数据
        List<SaleQualification> saleQualifications = new ArrayList<>();
        qualifications.forEach(qualification -> {
            SaleQualification saleQualification = new SaleQualification();
            //客户id
            saleQualification.setCustomerId(customer.getId());
            //活动id
            saleQualification.setSaleId(qualification.getSaleId());
            //设置活动的房源总数
            int saleHouseNum = houseOrderApi.countHouseBySaleId(qualification.getSaleId());
            saleQualification.setQualificationCount(saleHouseNum);
            //把准备好的数据放到容器中
            saleQualifications.add(saleQualification);
        });
        //保存活动数据，保存house-order冗余的活动数据sale_qualification
        houseOrderApi.updateSaleQualification(saleQualifications);
        return true;
    }

    //根据id删除客户信息
    public void removeCustomer(int id){
        userApi.removeUser(id);
        houseOrderApi.removeSaleQualification(id);
        customerDao.delete(id);
    }
}
